3 * User interface for the difference engine.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup DifferenceEngine
24 use MediaWiki\Storage\RevisionRecord
;
27 * DifferenceEngine is responsible for rendering the difference between two revisions as HTML.
28 * This includes interpreting URL parameters, retrieving revision data, checking access permissions,
29 * selecting and invoking the diff generator class for the individual slots, doing post-processing
30 * on the generated diff, adding the rest of the HTML (such as headers) and writing the whole thing
33 * DifferenceEngine can be subclassed by extensions, by customizing
34 * ContentHandler::createDifferenceEngine; the content handler will be selected based on the
35 * content model of the main slot (of the new revision, when the two are different).
36 * That might change after PageTypeHandler gets introduced.
38 * In the past, the class was also used for slot-level diff generation, and extensions might still
39 * subclass it and add such functionality. When that is the case (sepcifically, when a
40 * ContentHandler returns a standard SlotDiffRenderer but a nonstandard DifferenceEngine)
41 * DifferenceEngineSlotDiffRenderer will be used to convert the old behavior into the new one.
43 * @ingroup DifferenceEngine
45 * @todo This class is huge and poorly defined. It should be split into a controller responsible
46 * for interpreting query parameters, retrieving data and checking permissions; and a HTML renderer.
48 class DifferenceEngine
extends ContextSource
{
50 use DeprecationHelper
;
53 * Constant to indicate diff cache compatibility.
54 * Bump this when changing the diff formatting in a way that
55 * fixes important bugs or such to force cached diff views to
58 const DIFF_VERSION
= '1.12';
60 /** @var int Revision ID or 0 for current */
63 /** @var int|string Revision ID or null for current or an alias such as 'next' */
70 * Old revision (left pane).
71 * Allowed to be an unsaved revision, unlikely that's ever needed though.
72 * Null when the old revision does not exist; this can happen when using
73 * diff=prev on the first revision.
74 * Since 1.32 public access is deprecated.
80 * New revision (right pane).
81 * Note that this might be an unsaved revision (e.g. for edit preview).
82 * Null only in case of load failure; diff methods will just return an error message in that case.
83 * Since 1.32 public access is deprecated.
89 * Title of $mOldRev or null if the old revision does not exist or does not belong to a page.
90 * Since 1.32 public access is deprecated and the property can be null.
96 * Title of $mNewRev or null if the new revision does not exist or does not belong to a page.
97 * Since 1.32 public access is deprecated and the property can be null.
104 * @deprecated since 1.32, content slots are now handled by the corresponding SlotDiffRenderer.
105 * This property is set to the content of the main slot, but not actually used for the main diff.
107 private $mOldContent;
111 * @deprecated since 1.32, content slots are now handled by the corresponding SlotDiffRenderer.
112 * This property is set to the content of the main slot, but not actually used for the main diff.
114 private $mNewContent;
117 protected $mDiffLang;
119 /** @var bool Have the revisions IDs been loaded */
120 private $mRevisionsIdsLoaded = false;
122 /** @var bool Have the revisions been loaded */
123 protected $mRevisionsLoaded = false;
125 /** @var int How many text blobs have been loaded, 0, 1 or 2? */
126 protected $mTextLoaded = 0;
129 * Was the content overridden via setContent()?
130 * If the content was overridden, most internal state (e.g. mOldid or mOldRev) should be ignored
131 * and only mOldContent and mNewContent is reliable.
132 * (Note that setRevisions() does not set this flag as in that case all properties are
133 * overriden and remain consistent with each other, so no special handling is needed.)
136 protected $isContentOverridden = false;
138 /** @var bool Was the diff fetched from cache? */
139 protected $mCacheHit = false;
142 * Set this to true to add debug info to the HTML output.
143 * Warning: this may cause RSS readers to spuriously mark articles as "new"
146 public $enableDebugComment = false;
148 /** @var bool If true, line X is not displayed when X is 1, for example
149 * to increase readability and conserve space with many small diffs.
151 protected $mReducedLineNumbers = false;
153 /** @var string Link to action=markpatrolled */
154 protected $mMarkPatrolledLink = null;
156 /** @var bool Show rev_deleted content if allowed */
157 protected $unhide = false;
159 /** @var bool Refresh the diff cache */
160 protected $mRefreshCache = false;
162 /** @var SlotDiffRenderer[] DifferenceEngine classes for the slots, keyed by role name. */
163 protected $slotDiffRenderers = null;
166 * Temporary hack for B/C while slot diff related methods of DifferenceEngine are being
167 * deprecated. When true, we are inside a DifferenceEngineSlotDiffRenderer and
168 * $slotDiffRenderers should not be used.
171 protected $isSlotDiffRenderer = false;
176 * @param IContextSource|null $context Context to use, anything else will be ignored
177 * @param int $old Old ID we want to show and diff with.
178 * @param string|int $new Either revision ID or 'prev' or 'next'. Default: 0.
179 * @param int $rcid Deprecated, no longer used!
180 * @param bool $refreshCache If set, refreshes the diff cache
181 * @param bool $unhide If set, allow viewing deleted revs
183 public function __construct( $context = null, $old = 0, $new = 0, $rcid = 0,
184 $refreshCache = false, $unhide = false
186 $this->deprecatePublicProperty( 'mOldid', '1.32', __CLASS__
);
187 $this->deprecatePublicProperty( 'mNewid', '1.32', __CLASS__
);
188 $this->deprecatePublicProperty( 'mOldRev', '1.32', __CLASS__
);
189 $this->deprecatePublicProperty( 'mNewRev', '1.32', __CLASS__
);
190 $this->deprecatePublicProperty( 'mOldPage', '1.32', __CLASS__
);
191 $this->deprecatePublicProperty( 'mNewPage', '1.32', __CLASS__
);
192 $this->deprecatePublicProperty( 'mOldContent', '1.32', __CLASS__
);
193 $this->deprecatePublicProperty( 'mNewContent', '1.32', __CLASS__
);
194 $this->deprecatePublicProperty( 'mRevisionsLoaded', '1.32', __CLASS__
);
195 $this->deprecatePublicProperty( 'mTextLoaded', '1.32', __CLASS__
);
196 $this->deprecatePublicProperty( 'mCacheHit', '1.32', __CLASS__
);
198 if ( $context instanceof IContextSource
) {
199 $this->setContext( $context );
202 wfDebug( "DifferenceEngine old '$old' new '$new' rcid '$rcid'\n" );
204 $this->mOldid
= $old;
205 $this->mNewid
= $new;
206 $this->mRefreshCache
= $refreshCache;
207 $this->unhide
= $unhide;
211 * @return SlotDiffRenderer[] Diff renderers for each slot, keyed by role name.
212 * Includes slots only present in one of the revisions.
214 protected function getSlotDiffRenderers() {
215 if ( $this->isSlotDiffRenderer
) {
216 throw new LogicException( __METHOD__
. ' called in slot diff renderer mode' );
219 if ( $this->slotDiffRenderers
=== null ) {
220 if ( !$this->loadRevisionData() ) {
224 $slotContents = $this->getSlotContents();
225 $this->slotDiffRenderers
= array_map( function ( $contents ) {
226 /** @var $content Content */
227 $content = $contents['new'] ?
: $contents['old'];
228 return $content->getContentHandler()->getSlotDiffRenderer( $this->getContext() );
231 return $this->slotDiffRenderers
;
235 * Mark this DifferenceEngine as a slot renderer (as opposed to a page renderer).
236 * This is used in legacy mode when the DifferenceEngine is wrapped in a
237 * DifferenceEngineSlotDiffRenderer.
238 * @internal For use by DifferenceEngineSlotDiffRenderer only.
240 public function markAsSlotDiffRenderer() {
241 $this->isSlotDiffRenderer
= true;
245 * Get the old and new content objects for all slots.
246 * This method does not do any permission checks.
247 * @return array [ role => [ 'old' => SlotRecord, 'new' => SlotRecord ], ... ]
249 protected function getSlotContents() {
250 if ( $this->isContentOverridden
) {
253 'old' => $this->mOldContent
,
254 'new' => $this->mNewContent
,
259 $oldRev = $this->mOldRev
->getRevisionRecord();
260 $newRev = $this->mNewRev
->getRevisionRecord();
261 // The order here will determine the visual order of the diff. The current logic is
262 // changed first, then added, then deleted. This is ad hoc and should not be relied on
263 // - in the future we may want the ordering to depend on the page type.
264 $roles = array_merge( $newRev->getSlotRoles(), $oldRev->getSlotRoles() );
265 $oldSlots = $oldRev->getSlots()->getSlots();
266 $newSlots = $newRev->getSlots()->getSlots();
269 foreach ( $roles as $role ) {
271 'old' => isset( $oldSlots[$role] ) ?
$oldSlots[$role]->getContent() : null,
272 'new' => isset( $newSlots[$role] ) ?
$newSlots[$role]->getContent() : null,
275 // move main slot to front
276 if ( isset( $slots['main'] ) ) {
277 $slots = [ 'main' => $slots['main'] ] +
$slots;
283 * Set reduced line numbers mode.
284 * When set, line X is not displayed when X is 1, for example to increase readability and
285 * conserve space with many small diffs.
288 public function setReducedLineNumbers( $value = true ) {
289 $this->mReducedLineNumbers
= $value;
293 * Get the language of the difference engine, defaults to page content language
297 public function getDiffLang() {
298 if ( $this->mDiffLang
=== null ) {
299 # Default language in which the diff text is written.
300 $this->mDiffLang
= $this->getTitle()->getPageLanguage();
303 return $this->mDiffLang
;
309 public function wasCacheHit() {
310 return $this->mCacheHit
;
316 public function getOldid() {
317 $this->loadRevisionIds();
319 return $this->mOldid
;
325 public function getNewid() {
326 $this->loadRevisionIds();
328 return $this->mNewid
;
332 * Get the left side of the diff.
333 * Could be null when the first revision of the page is diffed to 'prev' (or in the case of
335 * @return RevisionRecord|null
337 public function getOldRevision() {
338 return $this->mOldRev ?
$this->mOldRev
->getRevisionRecord() : null;
342 * Get the right side of the diff.
343 * Should not be null but can still happen in the case of load failure.
344 * @return RevisionRecord|null
346 public function getNewRevision() {
347 return $this->mNewRev ?
$this->mNewRev
->getRevisionRecord() : null;
351 * Look up a special:Undelete link to the given deleted revision id,
352 * as a workaround for being unable to load deleted diffs in currently.
354 * @param int $id Revision ID
356 * @return string|bool Link HTML or false
358 public function deletedLink( $id ) {
359 if ( $this->getUser()->isAllowed( 'deletedhistory' ) ) {
360 $dbr = wfGetDB( DB_REPLICA
);
361 $arQuery = Revision
::getArchiveQueryInfo();
362 $row = $dbr->selectRow(
364 array_merge( $arQuery['fields'], [ 'ar_namespace', 'ar_title' ] ),
365 [ 'ar_rev_id' => $id ],
371 $rev = Revision
::newFromArchiveRow( $row );
372 $title = Title
::makeTitleSafe( $row->ar_namespace
, $row->ar_title
);
374 return SpecialPage
::getTitleFor( 'Undelete' )->getFullURL( [
375 'target' => $title->getPrefixedText(),
376 'timestamp' => $rev->getTimestamp()
385 * Build a wikitext link toward a deleted revision, if viewable.
387 * @param int $id Revision ID
389 * @return string Wikitext fragment
391 public function deletedIdMarker( $id ) {
392 $link = $this->deletedLink( $id );
394 return "[$link $id]";
400 private function showMissingRevision() {
401 $out = $this->getOutput();
404 if ( $this->mOldRev
=== null ||
405 ( $this->mOldRev
&& $this->mOldContent
=== null )
407 $missing[] = $this->deletedIdMarker( $this->mOldid
);
409 if ( $this->mNewRev
=== null ||
410 ( $this->mNewRev
&& $this->mNewContent
=== null )
412 $missing[] = $this->deletedIdMarker( $this->mNewid
);
415 $out->setPageTitle( $this->msg( 'errorpagetitle' ) );
416 $msg = $this->msg( 'difference-missing-revision' )
417 ->params( $this->getLanguage()->listToText( $missing ) )
418 ->numParams( count( $missing ) )
420 $out->addHTML( $msg );
423 public function showDiffPage( $diffOnly = false ) {
424 # Allow frames except in certain special cases
425 $out = $this->getOutput();
426 $out->allowClickjacking();
427 $out->setRobotPolicy( 'noindex,nofollow' );
429 // Allow extensions to add any extra output here
430 Hooks
::run( 'DifferenceEngineShowDiffPage', [ $out ] );
432 if ( !$this->loadRevisionData() ) {
433 if ( Hooks
::run( 'DifferenceEngineShowDiffPageMaybeShowMissingRevision', [ $this ] ) ) {
434 $this->showMissingRevision();
439 $user = $this->getUser();
441 if ( $this->mNewPage
) {
442 $permErrors = $this->mNewPage
->getUserPermissionsErrors( 'read', $user );
444 if ( $this->mOldPage
) {
445 $permErrors = wfMergeErrorArrays( $permErrors,
446 $this->mOldPage
->getUserPermissionsErrors( 'read', $user ) );
448 if ( count( $permErrors ) ) {
449 throw new PermissionsError( 'read', $permErrors );
455 # Carry over 'diffonly' param via navigation links
456 if ( $diffOnly != $user->getBoolOption( 'diffonly' ) ) {
457 $query['diffonly'] = $diffOnly;
459 # Cascade unhide param in links for easy deletion browsing
460 if ( $this->unhide
) {
461 $query['unhide'] = 1;
464 # Check if one of the revisions is deleted/suppressed
465 $deleted = $suppressed = false;
466 $allowed = $this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $user );
470 # mOldRev is false if the difference engine is called with a "vague" query for
471 # a diff between a version V and its previous version V' AND the version V
472 # is the first version of that article. In that case, V' does not exist.
473 if ( $this->mOldRev
=== false ) {
474 if ( $this->mNewPage
) {
475 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
479 // Allow extensions to change the $oldHeader variable
480 Hooks
::run( 'DifferenceEngineOldHeaderNoOldRev', [ &$oldHeader ] );
482 Hooks
::run( 'DiffViewHeader', [ $this, $this->mOldRev
, $this->mNewRev
] );
484 if ( !$this->mOldPage ||
!$this->mNewPage
) {
485 // XXX say something to the user?
487 } elseif ( $this->mNewPage
->equals( $this->mOldPage
) ) {
488 $out->setPageTitle( $this->msg( 'difference-title', $this->mNewPage
->getPrefixedText() ) );
491 $out->setPageTitle( $this->msg( 'difference-title-multipage',
492 $this->mOldPage
->getPrefixedText(), $this->mNewPage
->getPrefixedText() ) );
493 $out->addSubtitle( $this->msg( 'difference-multipage' ) );
497 if ( $samePage && $this->mNewPage
&& $this->mNewPage
->quickUserCan( 'edit', $user ) ) {
498 if ( $this->mNewRev
->isCurrent() && $this->mNewPage
->userCan( 'rollback', $user ) ) {
499 $rollbackLink = Linker
::generateRollback( $this->mNewRev
, $this->getContext() );
500 if ( $rollbackLink ) {
501 $out->preventClickjacking();
502 $rollback = "\u{00A0}\u{00A0}\u{00A0}" . $rollbackLink;
506 if ( !$this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) &&
507 !$this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
)
509 $undoLink = Html
::element( 'a', [
510 'href' => $this->mNewPage
->getLocalURL( [
512 'undoafter' => $this->mOldid
,
513 'undo' => $this->mNewid
515 'title' => Linker
::titleAttrib( 'undo' ),
517 $this->msg( 'editundo' )->text()
519 $revisionTools['mw-diff-undo'] = $undoLink;
523 # Make "previous revision link"
524 if ( $samePage && $this->mOldPage
&& $this->mOldRev
->getPrevious() ) {
525 $prevlink = Linker
::linkKnown(
527 $this->msg( 'previousdiff' )->escaped(),
528 [ 'id' => 'differences-prevlink' ],
529 [ 'diff' => 'prev', 'oldid' => $this->mOldid
] +
$query
532 $prevlink = "\u{00A0}";
535 if ( $this->mOldRev
->isMinor() ) {
536 $oldminor = ChangesList
::flag( 'minor' );
541 $ldel = $this->revisionDeleteLink( $this->mOldRev
);
542 $oldRevisionHeader = $this->getRevisionHeader( $this->mOldRev
, 'complete' );
543 $oldChangeTags = ChangeTags
::formatSummaryRow( $this->mOldTags
, 'diff', $this->getContext() );
545 $oldHeader = '<div id="mw-diff-otitle1"><strong>' . $oldRevisionHeader . '</strong></div>' .
546 '<div id="mw-diff-otitle2">' .
547 Linker
::revUserTools( $this->mOldRev
, !$this->unhide
) . '</div>' .
548 '<div id="mw-diff-otitle3">' . $oldminor .
549 Linker
::revComment( $this->mOldRev
, !$diffOnly, !$this->unhide
) . $ldel . '</div>' .
550 '<div id="mw-diff-otitle5">' . $oldChangeTags[0] . '</div>' .
551 '<div id="mw-diff-otitle4">' . $prevlink . '</div>';
553 // Allow extensions to change the $oldHeader variable
554 Hooks
::run( 'DifferenceEngineOldHeader', [ $this, &$oldHeader, $prevlink, $oldminor,
555 $diffOnly, $ldel, $this->unhide
] );
557 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
558 $deleted = true; // old revisions text is hidden
559 if ( $this->mOldRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
560 $suppressed = true; // also suppressed
564 # Check if this user can see the revisions
565 if ( !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $user ) ) {
570 $out->addJsConfigVars( [
571 'wgDiffOldId' => $this->mOldid
,
572 'wgDiffNewId' => $this->mNewid
,
575 # Make "next revision link"
576 # Skip next link on the top revision
577 if ( $samePage && $this->mNewPage
&& !$this->mNewRev
->isCurrent() ) {
578 $nextlink = Linker
::linkKnown(
580 $this->msg( 'nextdiff' )->escaped(),
581 [ 'id' => 'differences-nextlink' ],
582 [ 'diff' => 'next', 'oldid' => $this->mNewid
] +
$query
585 $nextlink = "\u{00A0}";
588 if ( $this->mNewRev
->isMinor() ) {
589 $newminor = ChangesList
::flag( 'minor' );
594 # Handle RevisionDelete links...
595 $rdel = $this->revisionDeleteLink( $this->mNewRev
);
597 # Allow extensions to define their own revision tools
598 Hooks
::run( 'DiffRevisionTools',
599 [ $this->mNewRev
, &$revisionTools, $this->mOldRev
, $user ] );
600 $formattedRevisionTools = [];
601 // Put each one in parentheses (poor man's button)
602 foreach ( $revisionTools as $key => $tool ) {
603 $toolClass = is_string( $key ) ?
$key : 'mw-diff-tool';
604 $element = Html
::rawElement(
606 [ 'class' => $toolClass ],
607 $this->msg( 'parentheses' )->rawParams( $tool )->escaped()
609 $formattedRevisionTools[] = $element;
611 $newRevisionHeader = $this->getRevisionHeader( $this->mNewRev
, 'complete' ) .
612 ' ' . implode( ' ', $formattedRevisionTools );
613 $newChangeTags = ChangeTags
::formatSummaryRow( $this->mNewTags
, 'diff', $this->getContext() );
615 $newHeader = '<div id="mw-diff-ntitle1"><strong>' . $newRevisionHeader . '</strong></div>' .
616 '<div id="mw-diff-ntitle2">' . Linker
::revUserTools( $this->mNewRev
, !$this->unhide
) .
618 '<div id="mw-diff-ntitle3">' . $newminor .
619 Linker
::revComment( $this->mNewRev
, !$diffOnly, !$this->unhide
) . $rdel . '</div>' .
620 '<div id="mw-diff-ntitle5">' . $newChangeTags[0] . '</div>' .
621 '<div id="mw-diff-ntitle4">' . $nextlink . $this->markPatrolledLink() . '</div>';
623 // Allow extensions to change the $newHeader variable
624 Hooks
::run( 'DifferenceEngineNewHeader', [ $this, &$newHeader, $formattedRevisionTools,
625 $nextlink, $rollback, $newminor, $diffOnly, $rdel, $this->unhide
] );
627 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_TEXT
) ) {
628 $deleted = true; // new revisions text is hidden
629 if ( $this->mNewRev
->isDeleted( Revision
::DELETED_RESTRICTED
) ) {
630 $suppressed = true; // also suppressed
634 # If the diff cannot be shown due to a deleted revision, then output
635 # the diff header and links to unhide (if available)...
636 if ( $deleted && ( !$this->unhide ||
!$allowed ) ) {
637 $this->showDiffStyle();
638 $multi = $this->getMultiNotice();
639 $out->addHTML( $this->addHeader( '', $oldHeader, $newHeader, $multi ) );
641 $msg = $suppressed ?
'rev-suppressed-no-diff' : 'rev-deleted-no-diff';
642 # Give explanation for why revision is not visible
643 $out->wrapWikiMsg( "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
646 # Give explanation and add a link to view the diff...
647 $query = $this->getRequest()->appendQueryValue( 'unhide', '1' );
648 $link = $this->getTitle()->getFullURL( $query );
649 $msg = $suppressed ?
'rev-suppressed-unhide-diff' : 'rev-deleted-unhide-diff';
651 "<div id='mw-$msg' class='mw-warning plainlinks'>\n$1\n</div>\n",
655 # Otherwise, output a regular diff...
657 # Add deletion notice if the user is viewing deleted content
660 $msg = $suppressed ?
'rev-suppressed-diff-view' : 'rev-deleted-diff-view';
661 $notice = "<div id='mw-$msg' class='mw-warning plainlinks'>\n" .
662 $this->msg( $msg )->parse() .
665 $this->showDiff( $oldHeader, $newHeader, $notice );
667 $this->renderNewRevision();
673 * Build a link to mark a change as patrolled.
675 * Returns empty string if there's either no revision to patrol or the user is not allowed to.
676 * Side effect: When the patrol link is build, this method will call
677 * OutputPage::preventClickjacking() and load mediawiki.page.patrol.ajax.
679 * @return string HTML or empty string
681 public function markPatrolledLink() {
682 if ( $this->mMarkPatrolledLink
=== null ) {
683 $linkInfo = $this->getMarkPatrolledLinkInfo();
684 // If false, there is no patrol link needed/allowed
685 if ( !$linkInfo ||
!$this->mNewPage
) {
686 $this->mMarkPatrolledLink
= '';
688 $this->mMarkPatrolledLink
= ' <span class="patrollink" data-mw="interface">[' .
691 $this->msg( 'markaspatrolleddiff' )->escaped(),
694 'action' => 'markpatrolled',
695 'rcid' => $linkInfo['rcid'],
698 // Allow extensions to change the markpatrolled link
699 Hooks
::run( 'DifferenceEngineMarkPatrolledLink', [ $this,
700 &$this->mMarkPatrolledLink
, $linkInfo['rcid'] ] );
703 return $this->mMarkPatrolledLink
;
707 * Returns an array of meta data needed to build a "mark as patrolled" link and
708 * adds the mediawiki.page.patrol.ajax to the output.
710 * @return array|false An array of meta data for a patrol link (rcid only)
711 * or false if no link is needed
713 protected function getMarkPatrolledLinkInfo() {
714 global $wgUseRCPatrol;
716 $user = $this->getUser();
718 // Prepare a change patrol link, if applicable
720 // Is patrolling enabled and the user allowed to?
721 $wgUseRCPatrol && $this->mNewPage
&& $this->mNewPage
->quickUserCan( 'patrol', $user ) &&
722 // Only do this if the revision isn't more than 6 hours older
723 // than the Max RC age (6h because the RC might not be cleaned out regularly)
724 RecentChange
::isInRCLifespan( $this->mNewRev
->getTimestamp(), 21600 )
726 // Look for an unpatrolled change corresponding to this diff
727 $db = wfGetDB( DB_REPLICA
);
728 $change = RecentChange
::newFromConds(
730 'rc_timestamp' => $db->timestamp( $this->mNewRev
->getTimestamp() ),
731 'rc_this_oldid' => $this->mNewid
,
732 'rc_patrolled' => RecentChange
::PRC_UNPATROLLED
737 if ( $change && !$change->getPerformer()->equals( $user ) ) {
738 $rcid = $change->getAttribute( 'rc_id' );
740 // None found or the page has been created by the current user.
741 // If the user could patrol this it already would be patrolled
745 // Allow extensions to possibly change the rcid here
746 // For example the rcid might be set to zero due to the user
747 // being the same as the performer of the change but an extension
748 // might still want to show it under certain conditions
749 Hooks
::run( 'DifferenceEngineMarkPatrolledRCID', [ &$rcid, $this, $change, $user ] );
753 $this->getOutput()->preventClickjacking();
754 if ( $user->isAllowed( 'writeapi' ) ) {
755 $this->getOutput()->addModules( 'mediawiki.page.patrol.ajax' );
764 // No mark as patrolled link applicable
769 * @param Revision $rev
773 protected function revisionDeleteLink( $rev ) {
774 $link = Linker
::getRevDeleteLink( $this->getUser(), $rev, $rev->getTitle() );
775 if ( $link !== '' ) {
776 $link = "\u{00A0}\u{00A0}\u{00A0}" . $link . ' ';
783 * Show the new revision of the page.
785 public function renderNewRevision() {
786 $out = $this->getOutput();
787 $revHeader = $this->getRevisionHeader( $this->mNewRev
);
788 # Add "current version as of X" title
789 $out->addHTML( "<hr class='diff-hr' id='mw-oldid' />
790 <h2 class='diff-currentversion-title'>{$revHeader}</h2>\n" );
791 # Page content may be handled by a hooked call instead...
792 if ( Hooks
::run( 'ArticleContentOnDiff', [ $this, $out ] ) ) {
793 $this->loadNewText();
794 if ( !$this->mNewPage
) {
795 // New revision is unsaved; bail out.
796 // TODO in theory rendering the new revision is a meaningful thing to do
797 // even if it's unsaved, but a lot of untangling is required to do it safely.
800 $out->setRevisionId( $this->mNewid
);
801 $out->setRevisionTimestamp( $this->mNewRev
->getTimestamp() );
802 $out->setArticleFlag( true );
804 if ( !Hooks
::run( 'ArticleContentViewCustom',
805 [ $this->mNewContent
, $this->mNewPage
, $out ] )
807 // Handled by extension
810 if ( $this->getTitle()->equals( $this->mNewPage
) ) {
811 // If the Title stored in the context is the same as the one
812 // of the new revision, we can use its associated WikiPage
814 $wikiPage = $this->getWikiPage();
816 // Otherwise we need to create our own WikiPage object
817 $wikiPage = WikiPage
::factory( $this->mNewPage
);
820 $parserOutput = $this->getParserOutput( $wikiPage, $this->mNewRev
);
822 # WikiPage::getParserOutput() should not return false, but just in case
823 if ( $parserOutput ) {
824 // Allow extensions to change parser output here
825 if ( Hooks
::run( 'DifferenceEngineRenderRevisionAddParserOutput',
826 [ $this, $out, $parserOutput, $wikiPage ] )
828 $out->addParserOutput( $parserOutput, [
829 'enableSectionEditLinks' => $this->mNewRev
->isCurrent()
830 && $this->mNewRev
->getTitle()->quickUserCan( 'edit', $this->getUser() ),
837 // Allow extensions to optionally not show the final patrolled link
838 if ( Hooks
::run( 'DifferenceEngineRenderRevisionShowFinalPatrolLink' ) ) {
839 # Add redundant patrol link on bottom...
840 $out->addHTML( $this->markPatrolledLink() );
845 * @param WikiPage $page
846 * @param Revision $rev
848 * @return ParserOutput|bool False if the revision was not found
850 protected function getParserOutput( WikiPage
$page, Revision
$rev ) {
851 $parserOptions = $page->makeParserOptions( $this->getContext() );
852 $parserOutput = $page->getParserOutput( $parserOptions, $rev->getId() );
854 return $parserOutput;
858 * Get the diff text, send it to the OutputPage object
859 * Returns false if the diff could not be generated, otherwise returns true
861 * @param string|bool $otitle Header for old text or false
862 * @param string|bool $ntitle Header for new text or false
863 * @param string $notice HTML between diff header and body
867 public function showDiff( $otitle, $ntitle, $notice = '' ) {
868 // Allow extensions to affect the output here
869 Hooks
::run( 'DifferenceEngineShowDiff', [ $this ] );
871 $diff = $this->getDiff( $otitle, $ntitle, $notice );
872 if ( $diff === false ) {
873 $this->showMissingRevision();
877 $this->showDiffStyle();
878 $this->getOutput()->addHTML( $diff );
885 * Add style sheets for diff display.
887 public function showDiffStyle() {
888 if ( !$this->isSlotDiffRenderer
) {
889 $this->getOutput()->addModuleStyles( 'mediawiki.diff.styles' );
890 foreach ( $this->getSlotDiffRenderers() as $slotDiffRenderer ) {
891 $slotDiffRenderer->addModules( $this->getOutput() );
897 * Get complete diff table, including header
899 * @param string|bool $otitle Header for old text or false
900 * @param string|bool $ntitle Header for new text or false
901 * @param string $notice HTML between diff header and body
905 public function getDiff( $otitle, $ntitle, $notice = '' ) {
906 $body = $this->getDiffBody();
907 if ( $body === false ) {
911 $multi = $this->getMultiNotice();
912 // Display a message when the diff is empty
913 if ( $body === '' ) {
914 $notice .= '<div class="mw-diff-empty">' .
915 $this->msg( 'diff-empty' )->parse() .
919 return $this->addHeader( $body, $otitle, $ntitle, $multi, $notice );
923 * Get the diff table body, without header
925 * @return mixed (string/false)
927 public function getDiffBody() {
928 $this->mCacheHit
= true;
929 // Check if the diff should be hidden from this user
930 if ( !$this->isContentOverridden
) {
931 if ( !$this->loadRevisionData() ) {
933 } elseif ( $this->mOldRev
&&
934 !$this->mOldRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
937 } elseif ( $this->mNewRev
&&
938 !$this->mNewRev
->userCan( Revision
::DELETED_TEXT
, $this->getUser() )
943 if ( $this->mOldRev
=== false ||
( $this->mOldRev
&& $this->mNewRev
&&
944 $this->mOldRev
->getId() && $this->mOldRev
->getId() == $this->mNewRev
->getId() )
946 if ( Hooks
::run( 'DifferenceEngineShowEmptyOldContent', [ $this ] ) ) {
954 $cache = ObjectCache
::getMainWANInstance();
955 if ( $this->mOldid
&& $this->mNewid
) {
956 // Check if subclass is still using the old way
957 // for backwards-compatibility
958 $key = $this->getDiffBodyCacheKey();
959 if ( $key === null ) {
960 $key = $cache->makeKey( ...$this->getDiffBodyCacheKeyParams() );
964 if ( !$this->mRefreshCache
) {
965 $difftext = $cache->get( $key );
967 wfIncrStats( 'diff_cache.hit' );
968 $difftext = $this->localiseDiff( $difftext );
969 $difftext .= "\n<!-- diff cache key $key -->\n";
973 } // don't try to load but save the result
975 $this->mCacheHit
= false;
977 // Loadtext is permission safe, this just clears out the diff
978 if ( !$this->loadText() ) {
983 // We've checked for revdelete at the beginning of this method; it's OK to ignore
984 // read permissions here.
985 $slotContents = $this->getSlotContents();
986 foreach ( $this->getSlotDiffRenderers() as $role => $slotDiffRenderer ) {
987 $slotDiff = $slotDiffRenderer->getDiff( $slotContents[$role]['old'],
988 $slotContents[$role]['new'] );
989 if ( $slotDiff && $role !== 'main' ) {
990 // TODO use human-readable role name at least
992 $difftext .= $this->getSlotHeader( $slotTitle );
994 $difftext .= $slotDiff;
997 // Avoid PHP 7.1 warning from passing $this by reference
1000 // Save to cache for 7 days
1001 if ( !Hooks
::run( 'AbortDiffCache', [ &$diffEngine ] ) ) {
1002 wfIncrStats( 'diff_cache.uncacheable' );
1003 } elseif ( $key !== false && $difftext !== false ) {
1004 wfIncrStats( 'diff_cache.miss' );
1005 $cache->set( $key, $difftext, 7 * 86400 );
1007 wfIncrStats( 'diff_cache.uncacheable' );
1009 // localise line numbers and title attribute text
1010 if ( $difftext !== false ) {
1011 $difftext = $this->localiseDiff( $difftext );
1018 * Get the diff table body for one slot, without header
1020 * @param string $role
1021 * @return string|false
1023 public function getDiffBodyForRole( $role ) {
1024 $diffRenderers = $this->getSlotDiffRenderers();
1025 if ( !isset( $diffRenderers[$role] ) ) {
1029 $slotContents = $this->getSlotContents();
1030 $slotDiff = $diffRenderers[$role]->getDiff( $slotContents[$role]['old'],
1031 $slotContents[$role]['new'] );
1036 if ( $role !== 'main' ) {
1037 // TODO use human-readable role name at least
1039 $slotDiff = $this->getSlotHeader( $slotTitle ) . $slotDiff;
1042 return $this->localiseDiff( $slotDiff );
1046 * Get a slot header for inclusion in a diff body (as a table row).
1048 * @param string $headerText The text of the header
1052 protected function getSlotHeader( $headerText ) {
1053 // The old revision is missing on oldid=<first>&diff=prev; only 2 columns in that case.
1054 $columnCount = $this->mOldRev ?
4 : 2;
1055 $userLang = $this->getLanguage()->getHtmlCode();
1056 return Html
::rawElement( 'tr', [ 'class' => 'mw-diff-slot-header', 'lang' => $userLang ],
1057 Html
::element( 'th', [ 'colspan' => $columnCount ], $headerText ) );
1061 * Returns the cache key for diff body text or content.
1063 * @deprecated since 1.31, use getDiffBodyCacheKeyParams() instead
1066 * @throws MWException
1067 * @return string|null
1069 protected function getDiffBodyCacheKey() {
1074 * Get the cache key parameters
1076 * Subclasses can replace the first element in the array to something
1077 * more specific to the type of diff (e.g. "inline-diff"), or append
1078 * if the cache should vary on more things. Overriding entirely should
1084 * @throws MWException
1086 protected function getDiffBodyCacheKeyParams() {
1087 if ( !$this->mOldid ||
!$this->mNewid
) {
1088 throw new MWException( 'mOldid and mNewid must be set to get diff cache key.' );
1091 $engine = $this->getEngine();
1096 "old-{$this->mOldid}",
1097 "rev-{$this->mNewid}"
1100 if ( $engine === 'wikidiff2' ) {
1101 $params[] = phpversion( 'wikidiff2' );
1102 $params[] = $this->getConfig()->get( 'WikiDiff2MovedParagraphDetectionCutoff' );
1105 if ( !$this->isSlotDiffRenderer
) {
1106 foreach ( $this->getSlotDiffRenderers() as $slotDiffRenderer ) {
1107 $params = array_merge( $params, $slotDiffRenderer->getExtraCacheKeys() );
1115 * Implements DifferenceEngineSlotDiffRenderer::getExtraCacheKeys(). Only used when
1116 * DifferenceEngine is wrapped in DifferenceEngineSlotDiffRenderer.
1118 * @internal for use by DifferenceEngineSlotDiffRenderer only
1121 public function getExtraCacheKeys() {
1122 // This method is called when the DifferenceEngine is used for a slot diff. We only care
1123 // about special things, not the revision IDs, which are added to the cache key by the
1124 // page-level DifferenceEngine, and which might not have a valid value for this object.
1125 $this->mOldid
= 123456789;
1126 $this->mNewid
= 987654321;
1128 // This will repeat a bunch of unnecessary key fields for each slot. Not nice but harmless.
1129 $cacheString = $this->getDiffBodyCacheKey();
1130 if ( $cacheString ) {
1131 return [ $cacheString ];
1134 $params = $this->getDiffBodyCacheKeyParams();
1136 // Try to get rid of the standard keys to keep the cache key human-readable:
1137 // call the getDiffBodyCacheKeyParams implementation of the base class, and if
1138 // the child class includes the same keys, drop them.
1139 // Uses an obscure PHP feature where static calls to non-static methods are allowed
1140 // as long as we are already in a non-static method of the same class, and the call context
1141 // ($this) will be inherited.
1142 // phpcs:ignore Squiz.Classes.SelfMemberReference.NotUsed
1143 $standardParams = DifferenceEngine
::getDiffBodyCacheKeyParams();
1144 if ( array_slice( $params, 0, count( $standardParams ) ) === $standardParams ) {
1145 $params = array_slice( $params, count( $standardParams ) );
1152 * Generate a diff, no caching.
1156 * @param Content $old Old content
1157 * @param Content $new New content
1159 * @throws Exception If old or new content is not an instance of TextContent.
1160 * @return bool|string
1162 * @deprecated since 1.32, use a SlotDiffRenderer instead.
1164 public function generateContentDiffBody( Content
$old, Content
$new ) {
1165 $slotDiffRenderer = $new->getContentHandler()->getSlotDiffRenderer( $this->getContext() );
1167 $slotDiffRenderer instanceof DifferenceEngineSlotDiffRenderer
1168 && $this->isSlotDiffRenderer
1170 // Oops, we are just about to enter an infinite loop (the slot-level DifferenceEngine
1171 // called a DifferenceEngineSlotDiffRenderer that wraps the same DifferenceEngine class).
1172 // This will happen when a content model has no custom slot diff renderer, it does have
1173 // a custom difference engine, but that does not override this method.
1174 throw new Exception( get_class( $this ) . ': could not maintain backwards compatibility. '
1175 . 'Please use a SlotDiffRenderer.' );
1177 return $slotDiffRenderer->getDiff( $old, $new ) . $this->getDebugString();
1181 * Generate a diff, no caching
1183 * @param string $otext Old text, must be already segmented
1184 * @param string $ntext New text, must be already segmented
1186 * @throws Exception If content handling for text content is configured in a way
1187 * that makes maintaining B/C hard.
1188 * @return bool|string
1190 * @deprecated since 1.32, use a TextSlotDiffRenderer instead.
1192 public function generateTextDiffBody( $otext, $ntext ) {
1193 $slotDiffRenderer = ContentHandler
::getForModelID( CONTENT_MODEL_TEXT
)
1194 ->getSlotDiffRenderer( $this->getContext() );
1195 if ( !( $slotDiffRenderer instanceof TextSlotDiffRenderer
) ) {
1196 // Someone used the GetSlotDiffRenderer hook to replace the renderer.
1197 // This is too unlikely to happen to bother handling properly.
1198 throw new Exception( 'The slot diff renderer for text content should be a '
1199 . 'TextSlotDiffRenderer subclass' );
1201 return $slotDiffRenderer->getTextDiff( $otext, $ntext ) . $this->getDebugString();
1205 * Process $wgExternalDiffEngine and get a sane, usable engine
1207 * @return bool|string 'wikidiff2', path to an executable, or false
1208 * @internal For use by this class and TextSlotDiffRenderer only.
1210 public static function getEngine() {
1211 global $wgExternalDiffEngine;
1212 // We use the global here instead of Config because we write to the value,
1213 // and Config is not mutable.
1214 if ( $wgExternalDiffEngine == 'wikidiff' ||
$wgExternalDiffEngine == 'wikidiff3' ) {
1215 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.27' );
1216 $wgExternalDiffEngine = false;
1217 } elseif ( $wgExternalDiffEngine == 'wikidiff2' ) {
1218 wfDeprecated( "\$wgExternalDiffEngine = '{$wgExternalDiffEngine}'", '1.32' );
1219 $wgExternalDiffEngine = false;
1220 } elseif ( !is_string( $wgExternalDiffEngine ) && $wgExternalDiffEngine !== false ) {
1221 // And prevent people from shooting themselves in the foot...
1222 wfWarn( '$wgExternalDiffEngine is set to a non-string value, forcing it to false' );
1223 $wgExternalDiffEngine = false;
1226 if ( is_string( $wgExternalDiffEngine ) && is_executable( $wgExternalDiffEngine ) ) {
1227 return $wgExternalDiffEngine;
1228 } elseif ( $wgExternalDiffEngine === false && function_exists( 'wikidiff2_do_diff' ) ) {
1237 * Generates diff, to be wrapped internally in a logging/instrumentation
1239 * @param string $otext Old text, must be already segmented
1240 * @param string $ntext New text, must be already segmented
1242 * @throws Exception If content handling for text content is configured in a way
1243 * that makes maintaining B/C hard.
1244 * @return bool|string
1246 * @deprecated since 1.32, use a TextSlotDiffRenderer instead.
1248 protected function textDiff( $otext, $ntext ) {
1249 $slotDiffRenderer = ContentHandler
::getForModelID( CONTENT_MODEL_TEXT
)
1250 ->getSlotDiffRenderer( $this->getContext() );
1251 if ( !( $slotDiffRenderer instanceof TextSlotDiffRenderer
) ) {
1252 // Someone used the GetSlotDiffRenderer hook to replace the renderer.
1253 // This is too unlikely to happen to bother handling properly.
1254 throw new Exception( 'The slot diff renderer for text content should be a '
1255 . 'TextSlotDiffRenderer subclass' );
1257 return $slotDiffRenderer->getTextDiff( $otext, $ntext ) . $this->getDebugString();
1261 * Generate a debug comment indicating diff generating time,
1262 * server node, and generator backend.
1264 * @param string $generator : What diff engine was used
1268 protected function debug( $generator = "internal" ) {
1269 global $wgShowHostnames;
1270 if ( !$this->enableDebugComment
) {
1273 $data = [ $generator ];
1274 if ( $wgShowHostnames ) {
1275 $data[] = wfHostname();
1277 $data[] = wfTimestamp( TS_DB
);
1279 return "<!-- diff generator: " .
1280 implode( " ", array_map( "htmlspecialchars", $data ) ) .
1284 private function getDebugString() {
1285 $engine = self
::getEngine();
1286 if ( $engine === 'wikidiff2' ) {
1287 return $this->debug( 'wikidiff2' );
1288 } elseif ( $engine === false ) {
1289 return $this->debug( 'native PHP' );
1291 return $this->debug( "external $engine" );
1296 * Localise diff output
1298 * @param string $text
1301 private function localiseDiff( $text ) {
1302 $text = $this->localiseLineNumbers( $text );
1303 if ( $this->getEngine() === 'wikidiff2' &&
1304 version_compare( phpversion( 'wikidiff2' ), '1.5.1', '>=' )
1306 $text = $this->addLocalisedTitleTooltips( $text );
1312 * Replace line numbers with the text in the user's language
1314 * @param string $text
1318 public function localiseLineNumbers( $text ) {
1319 return preg_replace_callback(
1320 '/<!--LINE (\d+)-->/',
1321 [ $this, 'localiseLineNumbersCb' ],
1326 public function localiseLineNumbersCb( $matches ) {
1327 if ( $matches[1] === '1' && $this->mReducedLineNumbers
) {
1331 return $this->msg( 'lineno' )->numParams( $matches[1] )->escaped();
1335 * Add title attributes for tooltips on moved paragraph indicators
1337 * @param string $text
1340 private function addLocalisedTitleTooltips( $text ) {
1341 return preg_replace_callback(
1342 '/class="mw-diff-movedpara-(left|right)"/',
1343 [ $this, 'addLocalisedTitleTooltipsCb' ],
1349 * @param array $matches
1352 private function addLocalisedTitleTooltipsCb( array $matches ) {
1353 $key = $matches[1] === 'right' ?
1354 'diff-paragraph-moved-toold' :
1355 'diff-paragraph-moved-tonew';
1356 return $matches[0] . ' title="' . $this->msg( $key )->escaped() . '"';
1360 * If there are revisions between the ones being compared, return a note saying so.
1364 public function getMultiNotice() {
1365 // The notice only make sense if we are diffing two saved revisions of the same page.
1367 !$this->mOldRev ||
!$this->mNewRev
1368 ||
!$this->mOldPage ||
!$this->mNewPage
1369 ||
!$this->mOldPage
->equals( $this->mNewPage
)
1374 if ( $this->mOldRev
->getTimestamp() > $this->mNewRev
->getTimestamp() ) {
1375 $oldRev = $this->mNewRev
; // flip
1376 $newRev = $this->mOldRev
; // flip
1377 } else { // normal case
1378 $oldRev = $this->mOldRev
;
1379 $newRev = $this->mNewRev
;
1382 // Sanity: don't show the notice if too many rows must be scanned
1383 // @todo show some special message for that case
1384 $nEdits = $this->mNewPage
->countRevisionsBetween( $oldRev, $newRev, 1000 );
1385 if ( $nEdits > 0 && $nEdits <= 1000 ) {
1386 $limit = 100; // use diff-multi-manyusers if too many users
1387 $users = $this->mNewPage
->getAuthorsBetween( $oldRev, $newRev, $limit );
1388 $numUsers = count( $users );
1390 if ( $numUsers == 1 && $users[0] == $newRev->getUserText( Revision
::RAW
) ) {
1391 $numUsers = 0; // special case to say "by the same user" instead of "by one other user"
1394 return self
::intermediateEditsMsg( $nEdits, $numUsers, $limit );
1397 return ''; // nothing
1401 * Get a notice about how many intermediate edits and users there are
1403 * @param int $numEdits
1404 * @param int $numUsers
1409 public static function intermediateEditsMsg( $numEdits, $numUsers, $limit ) {
1410 if ( $numUsers === 0 ) {
1411 $msg = 'diff-multi-sameuser';
1412 } elseif ( $numUsers > $limit ) {
1413 $msg = 'diff-multi-manyusers';
1416 $msg = 'diff-multi-otherusers';
1419 return wfMessage( $msg )->numParams( $numEdits, $numUsers )->parse();
1423 * Get a header for a specified revision.
1425 * @param Revision $rev
1426 * @param string $complete 'complete' to get the header wrapped depending
1427 * the visibility of the revision and a link to edit the page.
1429 * @return string HTML fragment
1431 public function getRevisionHeader( Revision
$rev, $complete = '' ) {
1432 $lang = $this->getLanguage();
1433 $user = $this->getUser();
1434 $revtimestamp = $rev->getTimestamp();
1435 $timestamp = $lang->userTimeAndDate( $revtimestamp, $user );
1436 $dateofrev = $lang->userDate( $revtimestamp, $user );
1437 $timeofrev = $lang->userTime( $revtimestamp, $user );
1439 $header = $this->msg(
1440 $rev->isCurrent() ?
'currentrev-asof' : 'revisionasof',
1446 if ( $complete !== 'complete' ) {
1450 $title = $rev->getTitle();
1452 $header = Linker
::linkKnown( $title, $header, [],
1453 [ 'oldid' => $rev->getId() ] );
1455 if ( $rev->userCan( Revision
::DELETED_TEXT
, $user ) ) {
1456 $editQuery = [ 'action' => 'edit' ];
1457 if ( !$rev->isCurrent() ) {
1458 $editQuery['oldid'] = $rev->getId();
1461 $key = $title->quickUserCan( 'edit', $user ) ?
'editold' : 'viewsourceold';
1462 $msg = $this->msg( $key )->escaped();
1463 $editLink = $this->msg( 'parentheses' )->rawParams(
1464 Linker
::linkKnown( $title, $msg, [], $editQuery ) )->escaped();
1465 $header .= ' ' . Html
::rawElement(
1467 [ 'class' => 'mw-diff-edit' ],
1470 if ( $rev->isDeleted( Revision
::DELETED_TEXT
) ) {
1471 $header = Html
::rawElement(
1473 [ 'class' => 'history-deleted' ],
1478 $header = Html
::rawElement( 'span', [ 'class' => 'history-deleted' ], $header );
1485 * Add the header to a diff body
1487 * @param string $diff Diff body
1488 * @param string $otitle Old revision header
1489 * @param string $ntitle New revision header
1490 * @param string $multi Notice telling user that there are intermediate
1491 * revisions between the ones being compared
1492 * @param string $notice Other notices, e.g. that user is viewing deleted content
1496 public function addHeader( $diff, $otitle, $ntitle, $multi = '', $notice = '' ) {
1497 // shared.css sets diff in interface language/dir, but the actual content
1498 // is often in a different language, mostly the page content language/dir
1499 $header = Html
::openElement( 'table', [
1500 'class' => [ 'diff', 'diff-contentalign-' . $this->getDiffLang()->alignStart() ],
1501 'data-mw' => 'interface',
1503 $userLang = htmlspecialchars( $this->getLanguage()->getHtmlCode() );
1505 if ( !$diff && !$otitle ) {
1507 <tr class=\"diff-title\" lang=\"{$userLang}\">
1508 <td class=\"diff-ntitle\">{$ntitle}</td>
1512 if ( $diff ) { // Safari/Chrome show broken output if cols not used
1514 <col class=\"diff-marker\" />
1515 <col class=\"diff-content\" />
1516 <col class=\"diff-marker\" />
1517 <col class=\"diff-content\" />";
1524 if ( $otitle ||
$ntitle ) {
1526 <tr class=\"diff-title\" lang=\"{$userLang}\">
1527 <td colspan=\"$colspan\" class=\"diff-otitle\">{$otitle}</td>
1528 <td colspan=\"$colspan\" class=\"diff-ntitle\">{$ntitle}</td>
1533 if ( $multi != '' ) {
1534 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
1535 "class=\"diff-multi\" lang=\"{$userLang}\">{$multi}</td></tr>";
1537 if ( $notice != '' ) {
1538 $header .= "<tr><td colspan=\"{$multiColspan}\" " .
1539 "class=\"diff-notice\" lang=\"{$userLang}\">{$notice}</td></tr>";
1542 return $header . $diff . "</table>";
1546 * Use specified text instead of loading from the database
1547 * @param Content $oldContent
1548 * @param Content $newContent
1550 * @deprecated since 1.32, use setRevisions or ContentHandler::getSlotDiffRenderer.
1552 public function setContent( Content
$oldContent, Content
$newContent ) {
1553 $this->mOldContent
= $oldContent;
1554 $this->mNewContent
= $newContent;
1556 $this->mTextLoaded
= 2;
1557 $this->mRevisionsLoaded
= true;
1558 $this->isContentOverridden
= true;
1559 $this->slotDiffRenderers
= null;
1563 * Use specified text instead of loading from the database.
1564 * @param RevisionRecord|null $oldRevision
1565 * @param RevisionRecord $newRevision
1567 public function setRevisions(
1568 RevisionRecord
$oldRevision = null, RevisionRecord
$newRevision
1570 if ( $oldRevision ) {
1571 $this->mOldRev
= new Revision( $oldRevision );
1572 $this->mOldid
= $oldRevision->getId();
1573 $this->mOldPage
= Title
::newFromLinkTarget( $oldRevision->getPageAsLinkTarget() );
1574 // This method is meant for edit diffs and such so there is no reason to provide a
1575 // revision that's not readable to the user, but check it just in case.
1576 $this->mOldContent
= $oldRevision ?
$oldRevision->getContent( 'main',
1577 RevisionRecord
::FOR_THIS_USER
, $this->getUser() ) : null;
1579 $this->mOldRev
= $this->mOldid
= $this->mOldPage
= null;
1581 $this->mNewRev
= new Revision( $newRevision );
1582 $this->mNewid
= $newRevision->getId();
1583 $this->mNewPage
= Title
::newFromLinkTarget( $newRevision->getPageAsLinkTarget() );
1584 $this->mNewContent
= $newRevision->getContent( 'main',
1585 RevisionRecord
::FOR_THIS_USER
, $this->getUser() );
1587 $this->mRevisionsIdsLoaded
= $this->mRevisionsLoaded
= true;
1588 $this->mTextLoaded
= !!$oldRevision +
1;
1589 $this->isContentOverridden
= false;
1590 $this->slotDiffRenderers
= null;
1594 * Set the language in which the diff text is written
1596 * @param Language $lang
1599 public function setTextLanguage( $lang ) {
1600 if ( !$lang instanceof Language
) {
1601 wfDeprecated( __METHOD__
. ' with other type than Language for $lang', '1.32' );
1603 $this->mDiffLang
= wfGetLangObj( $lang );
1607 * Maps a revision pair definition as accepted by DifferenceEngine constructor
1608 * to a pair of actual integers representing revision ids.
1610 * @param int $old Revision id, e.g. from URL parameter 'oldid'
1611 * @param int|string $new Revision id or strings 'next' or 'prev', e.g. from URL parameter 'diff'
1613 * @return int[] List of two revision ids, older first, later second.
1614 * Zero signifies invalid argument passed.
1615 * false signifies that there is no previous/next revision ($old is the oldest/newest one).
1617 public function mapDiffPrevNext( $old, $new ) {
1618 if ( $new === 'prev' ) {
1619 // Show diff between revision $old and the previous one. Get previous one from DB.
1620 $newid = intval( $old );
1621 $oldid = $this->getTitle()->getPreviousRevisionID( $newid );
1622 } elseif ( $new === 'next' ) {
1623 // Show diff between revision $old and the next one. Get next one from DB.
1624 $oldid = intval( $old );
1625 $newid = $this->getTitle()->getNextRevisionID( $oldid );
1627 $oldid = intval( $old );
1628 $newid = intval( $new );
1631 return [ $oldid, $newid ];
1637 private function loadRevisionIds() {
1638 if ( $this->mRevisionsIdsLoaded
) {
1642 $this->mRevisionsIdsLoaded
= true;
1644 $old = $this->mOldid
;
1645 $new = $this->mNewid
;
1647 list( $this->mOldid
, $this->mNewid
) = self
::mapDiffPrevNext( $old, $new );
1648 if ( $new === 'next' && $this->mNewid
=== false ) {
1649 # if no result, NewId points to the newest old revision. The only newer
1650 # revision is cur, which is "0".
1655 'NewDifferenceEngine',
1656 [ $this->getTitle(), &$this->mOldid
, &$this->mNewid
, $old, $new ]
1661 * Load revision metadata for the specified articles. If newid is 0, then compare
1662 * the old article in oldid to the current article; if oldid is 0, then
1663 * compare the current article to the immediately previous one (ignoring the
1666 * If oldid is false, leave the corresponding revision object set
1667 * to false. This is impossible via ordinary user input, and is provided for
1670 * @return bool Whether both revisions were loaded successfully.
1672 public function loadRevisionData() {
1673 if ( $this->mRevisionsLoaded
) {
1674 return $this->isContentOverridden ||
$this->mNewRev
&& $this->mOldRev
;
1677 // Whether it succeeds or fails, we don't want to try again
1678 $this->mRevisionsLoaded
= true;
1680 $this->loadRevisionIds();
1682 // Load the new revision object
1683 if ( $this->mNewid
) {
1684 $this->mNewRev
= Revision
::newFromId( $this->mNewid
);
1686 $this->mNewRev
= Revision
::newFromTitle(
1689 Revision
::READ_NORMAL
1693 if ( !$this->mNewRev
instanceof Revision
) {
1697 // Update the new revision ID in case it was 0 (makes life easier doing UI stuff)
1698 $this->mNewid
= $this->mNewRev
->getId();
1699 if ( $this->mNewid
) {
1700 $this->mNewPage
= $this->mNewRev
->getTitle();
1702 $this->mNewPage
= null;
1705 // Load the old revision object
1706 $this->mOldRev
= false;
1707 if ( $this->mOldid
) {
1708 $this->mOldRev
= Revision
::newFromId( $this->mOldid
);
1709 } elseif ( $this->mOldid
=== 0 ) {
1710 $rev = $this->mNewRev
->getPrevious();
1712 $this->mOldid
= $rev->getId();
1713 $this->mOldRev
= $rev;
1715 // No previous revision; mark to show as first-version only.
1716 $this->mOldid
= false;
1717 $this->mOldRev
= false;
1719 } /* elseif ( $this->mOldid === false ) leave mOldRev false; */
1721 if ( is_null( $this->mOldRev
) ) {
1725 if ( $this->mOldRev
&& $this->mOldRev
->getId() ) {
1726 $this->mOldPage
= $this->mOldRev
->getTitle();
1728 $this->mOldPage
= null;
1731 // Load tags information for both revisions
1732 $dbr = wfGetDB( DB_REPLICA
);
1733 if ( $this->mOldid
!== false ) {
1734 $this->mOldTags
= $dbr->selectField(
1737 [ 'ts_rev_id' => $this->mOldid
],
1741 $this->mOldTags
= false;
1743 $this->mNewTags
= $dbr->selectField(
1746 [ 'ts_rev_id' => $this->mNewid
],
1754 * Load the text of the revisions, as well as revision data.
1756 * @return bool Whether the content of both revisions could be loaded successfully.
1758 public function loadText() {
1759 if ( $this->mTextLoaded
== 2 ) {
1760 return $this->loadRevisionData() && $this->mOldContent
&& $this->mNewContent
;
1763 // Whether it succeeds or fails, we don't want to try again
1764 $this->mTextLoaded
= 2;
1766 if ( !$this->loadRevisionData() ) {
1770 if ( $this->mOldRev
) {
1771 $this->mOldContent
= $this->mOldRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1772 if ( $this->mOldContent
=== null ) {
1777 if ( $this->mNewRev
) {
1778 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1779 Hooks
::run( 'DifferenceEngineLoadTextAfterNewContentIsLoaded', [ $this ] );
1780 if ( $this->mNewContent
=== null ) {
1789 * Load the text of the new revision, not the old one
1791 * @return bool Whether the content of the new revision could be loaded successfully.
1793 public function loadNewText() {
1794 if ( $this->mTextLoaded
>= 1 ) {
1795 return $this->loadRevisionData();
1798 $this->mTextLoaded
= 1;
1800 if ( !$this->loadRevisionData() ) {
1804 $this->mNewContent
= $this->mNewRev
->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
1806 Hooks
::run( 'DifferenceEngineAfterLoadNewText', [ $this ] );